<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="编辑素材" width="650px" @ok="handleSubmit"
    showFooter destroyOnClose>
    <BasicForm @register="registerForm">
      <template #uploadFild="{ model, field }">
        <MyUpload v-model:value="model[field]" v-bind="uploadProps" ref="uploadRef" />
      </template>
    </BasicForm>

  </BasicDrawer>
</template>

<script lang="ts" setup>
import { ref, computed, unref, useAttrs, reactive } from 'vue';
import { BasicForm, useForm } from '/@/components/Form';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { materialFormSchema, getUploadBizType } from '../material.data';
import { saveOrUpdateMaterial } from '/@/api/infra/material';
import { listDataGroupTree } from '/@/api/infra/dataGroup.ts';
import { DataGroupBizType } from '/@/components/BizDataGroup/index';
import { useMessage } from '/@/hooks/web/useMessage';
import { MyUpload } from '/@/components/My/Upload/index';
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const uploadRef = ref<any>()
const [registerForm, { setProps, resetFields, setFieldsValue, getFieldsValue, validate, updateSchema }] = useForm({
  labelCol: {
    md: { span: 4 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 18 },
  },
  labelWidth: 80,
  schemas: materialFormSchema,
  showActionButtonGroup: false
})

const uploadProps = ref<any>({})

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  console.log('data', data);
  setDrawerProps({ confirmLoading: false });
  //获取下拉树信息
  const treeData = await listDataGroupTree({ bizType:  DataGroupBizType.MATERIAL, groupType: data.materialType});

  if (unref(isUpdate)) {
    setFieldsValue({ 
      ...data.record, 
      materialType: data.materialType,
      originUrl: data.record.url
    });
  }
  uploadProps.value = {
    maxCount: 1,
    accept: data.fileTypeLimit,
    bizType: getUploadBizType(data.materialType),
    immediate: false
  }

  updateSchema([
    {
      field: 'groupId',
      componentProps: { treeData },
    }, 
  ])
});


/**
 * 提交
 */
async function handleSubmit() {
  const formValue = getFieldsValue()
  if (!(formValue.url && formValue.url !== '')) {
    if (uploadRef.value.fileList.length == 0) {
      console.log('fileList', uploadRef.value.fileList)
      createMessage.warn('请选择文件')
      return
    }
    createMessage.loading({
      content: `正在上传文件...`,
      key: 'upload_material',
      duration: 0,
    });
 
    setTimeout(async () => {
      try {
        await uploadRef.value.startUpload({
          originUrl: formValue.originUrl,
          urlSign: formValue.urlSign
        })
        doSaveOrUpdate()
      } finally {
        createMessage.destroy('upload_material')
      }
    }, 1000)
  } else {
    doSaveOrUpdate()
  }
  
}

async function doSaveOrUpdate() {
  setDrawerProps({ confirmLoading: true })
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });

    const form : any = {...values}
    console.log("form: ", form);
    await saveOrUpdateMaterial(form, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`编辑成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
